/*
 *  YouTube Picker
 * 
 *  Copyright (c) 2014 Ted Hive <tedhive@gmail.com>
 *  
 *  Developed from YTD2 [ http://sourceforge.net/projects/ytd2/ ]
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package com.googlecode.youtubepicker;

import java.io.StringWriter;
import java.net.URL;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.w3c.dom.Node;

public class Tool {
	
    private static Logger logger = Logger.getLogger(Tool.class);
	
    public static void placeCentered(Shell shell) {
        Point size = shell.computeSize(-1, -1);
        placeCentered(shell, size.x, size.y);
    }

    public static void placeCentered(Shell shell, int width, int height) {
        Rectangle screen = Display.getCurrent().getBounds();
        shell.setLocation((screen.width - width) / 2, (screen.height - height) / 2);
    }
    
    public static int warningBox(Shell shell, String message) {
        return messageBox(shell, "Warning", SWT.ICON_WARNING | SWT.OK, message);
    }

    public static int confirmBox(Shell shell, String message) {
        return messageBox(shell, "Confirmation", SWT.ICON_QUESTION | SWT.YES | SWT.NO, message);
    }
    
    public static int errorBox(Shell shell, Exception e) {
        return errorBox(shell, getMessage(e)); 
    }
    
    public static String getMessage(Exception e) {
        String msg = "";
        if (e.getCause() != null) {
                if (e.getCause().getMessage() != null) {
                        msg = e.getCause().getMessage();
                } else {
                        msg = e.getCause().toString();
                }
        } else {
                if (e.getMessage() != null) {
                        msg = e.getMessage();
                } else {
                        msg = e.toString();
                }
        }
        return msg;
    }
    
    public static int errorBox(Shell shell, String message) {
        return messageBox(shell, "Error", SWT.OK | SWT.ICON_ERROR, message);
    }
    
    public static int messageBox(Shell shell, String title, int uiProps, String message) {
        MessageBox mb = new MessageBox(shell, uiProps);
        if(title != null && title.length() > 0) {
            mb.setText(title);
        }
        mb.setMessage(message);
        return mb.open();
    }

    public static int infoBox(Shell shell, String message) {
        return messageBox(shell, "Information", SWT.OK | SWT.ICON_INFORMATION, message);
    }
	
    public static void sleep(long src) {
    	try {
    		Thread.sleep(src);
    	} catch (Exception e) {
    	}
    }
    
	public static String xmlToString(Node node) {
	    String returnString = "";
	    try {
	        //create string from xml tree
	        //Output the XML
	        //set up a transformer
	        TransformerFactory transfac = TransformerFactory.newInstance();
	        Transformer trans;
	        trans = transfac.newTransformer();
	        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	        trans.setOutputProperty(OutputKeys.INDENT, "yes");
	        StringWriter sw = new StringWriter();
	        StreamResult streamResult = new StreamResult(sw);
	        DOMSource source = new DOMSource(node);
	        trans.transform(source, streamResult);
	        String xmlString = sw.toString();
	        //print the XML
	        returnString = returnString + xmlString;
	    } catch (TransformerException ex) {
	    }
	    return returnString;
	}
    
	public static String replace(String src, String pattern, String replacement) {
		String tag = "";
		int begin = 0;
		int pos = 0;
		pos = src.indexOf(pattern, begin);
		while (pos >= 0) {
			tag += src.substring(begin, pos) + replacement;
			begin = pos + pattern.length();
			pos = src.indexOf(pattern, begin);
		}
		tag += src.substring(begin);
		return tag;
	}
	
	public static boolean validYouTubeLink(String src) {
		try {
			URL url = new URL(src);
			String host = url.getHost().toLowerCase();
			if (host.startsWith("www.")) {
				host = host.substring(4);
			}
			if (!host.startsWith("youtube.") && !host.equals("youtu.be")) {
				return false;
			}
			String[] fs = host.split("\\.");
			if (fs.length != 2) {
				return false;
			}
			String videoId = "";
			if (host.equals("youtu.be")) {
				String path = url.getPath();
				if (path.startsWith("/")) {
					path = path.substring(1);
				}
				int pos = path.indexOf("/");
				if (pos >= 0) {
					return false;
				}
				if (path.trim().length() == 0) {
					return false;
				}
				String qr = url.getQuery();
				if (qr != null) {
					if (qr.length() > 0) {
						return false;
					}
					if (src.endsWith("?")) {
						return false;
					}
				}
				videoId = path;
			} else {
				String path = url.getPath();
				if (path.startsWith("/")) {
					path = path.substring(1);
				}
				if (!path.equals("watch")) {
					return false;
				}
				String qr = url.getQuery();
				if (qr != null) {
					boolean found = false;
					fs = qr.split("&");
					for (int i = 0; i < fs.length; i++) {
						if (fs[i].startsWith("v=")) {
							videoId = fs[i].substring(2);
							if (videoId.trim().length() > 0) {
								found = true;
							}
						}
					}
					if (!found) {
						return false;
					}
				}
			}
		
			Connection conn = Jsoup.connect(src);
			conn.timeout(60000);
			conn.followRedirects(true);
			conn.userAgent("Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.132 Safari/537.36 OPR/21.0.1432.67");
			conn.execute();
		} catch (Throwable t) {
			return false;
		}
		return true;
	}

	public static String getYouTubeVideoId(String src) {
		String videoId = "";
		try {
			URL url = new URL(src);
			String host = url.getHost().toLowerCase();
			if (host.startsWith("www.")) {
				host = host.substring(4);
			}
			if (host.equals("youtu.be")) {
				String path = url.getPath();
				if (path.startsWith("/")) {
					path = path.substring(1);
				}
				videoId = path;
			} else {
				boolean found = false;
				String[] fs = url.getQuery().split("&");
				for (int i = 0; i < fs.length; i++) {
					if (fs[i].startsWith("v=")) {
						videoId = fs[i].substring(2);
						if (videoId.trim().length() > 0) {
							found = true;
						}
					}
				}
				if (!found) {
					videoId = "";
				}
			}
		} catch (Throwable t) {
			return "";
		}
		return videoId;
	}
	
}
